﻿var ajaxPost = function (url, parms, onSuccess) {
    ajaxCall('POST', url, parms, onSuccess);
}

var ajaxCall = function (type, url, parms, onSuccess) {
    $.ajax({
        type: type,
        url: url,
        data: parms,
        cache: false,
        dataType: 'json',
        success: function (result) {
            if (result.session_timedout == true) {
                handleSessionTimedOut();
            }
            else {
                onSuccess(result);
            }
        },
        error: function (xhr, status) {
            onAjaxErrorHandler(xhr, status);
        }
    });
}

var onAjaxErrorHandler = function (xhr, status) {
    try {
        toggleReportGridLoading(false);
    }
    catch (e) {
    }

    if (status == "parsererror") {
        try {
            handleSessionTimedOut();
        }
        catch (e) {
        }
    }
    else {
        alert(status);
    }
}

String.format = function () {
    var s = arguments[0];
    for (var i = 0; i < arguments.length - 1; i++) {
        var reg = new RegExp("\\{" + i + "\\}", "gm");
        s = s.replace(reg, arguments[i + 1]);
    }
    return s;
}

/* For file upload browse button to support locale */
function initUploadInputs(btnLabel) {
    var W3CDOM = (document.createElement && document.getElementsByTagName);
    if (!W3CDOM) return;

    var fFileUpload = document.createElement('div');
    fFileUpload.className = 'fkfile';

    var hdnInput = document.createElement('input');
    hdnInput.disabled = "disabled";
    hdnInput.readonly = "readonly";
    hdnInput.width = "152";
    hdnInput.className = "fkinput";
    hdnInput.onfocus = function () { this.focus(); };
    fFileUpload.appendChild(hdnInput);

    var btn = document.createElement('input');
    btn.type = "button";
    btn.className = "uploadbutton";
    btn.value = btnLabel;
    fFileUpload.appendChild(btn);

    var x = document.getElementsByTagName('input');
    for (var i = 0; i < x.length; i++) {
        if (x[i].type != 'file') continue;
        if (x[i].parentNode.className != 'fileinputs') continue;

        x[i].className = 'file hidden';
        var clone = fFileUpload.cloneNode(true);
        x[i].parentNode.appendChild(clone);
        x[i].relatedElement = clone.getElementsByTagName('input')[0];
        x[i].onchange = x[i].onmouseout = function () {
            this.relatedElement.value = this.value;
        }
    }
}